package com.example.campuslink.commen.adpter

import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.LifecycleOwner
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.core.CoreAdapter
import com.example.campuslink.commen.core.CoreViewHolder
import com.example.campuslink.commen.db.message.MessageTable
import com.example.campuslink.databinding.AdapterMessageShowItemBinding
import com.example.campuslink.viewModel.MessageViewModel

class MessageShowItemAdapter(vm: MessageViewModel) :
    CoreAdapter<AdapterMessageShowItemBinding, MessageViewModel, MessageTable>(
        BR.data,
        BR.viewModel,
        vm
    ) {
    override fun getItemLayoutId(viewType: Int): Int {
        return R.layout.adapter_message_show_item
    }

    override fun onBindViewHolder(holder: CoreViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        Glide.with(holder.itemView.context).load(mListData[position].messageImage)
            .error(R.drawable.ic_empty)
            .into(holder.binding.root.findViewById<ImageView>(R.id.iv_message_img))
        holder.binding.root.findViewById<TextView>(R.id.tv_message_content).text =
            mListData[position].messageContent
        holder.binding.apply {
            // 设置默认值
            root.findViewById<TextView>(R.id.tv_userName).text = "加载中..."
            Glide.with(holder.itemView.context).load(R.drawable.ic_empty)
                .apply(RequestOptions.circleCropTransform())
                .into(root.findViewById<ImageView>(R.id.iv_userImg))

            mViewModel?.getUserInfo(mListData[position].sendNumber)

            mViewModel?.userInfoMap?.observe(holder.itemView.context as LifecycleOwner) { map ->
                // 检查position是否有效
                if (position < mListData.size) {
                    map[mListData[position].sendNumber]?.let { info ->
                        root.findViewById<TextView>(R.id.tv_userName).text = info.userName
                        Glide.with(holder.itemView.context).load(info.userAvatar)
                            .error(R.drawable.ic_empty)
                            .into(root.findViewById<ImageView>(R.id.iv_userImg))
                    }
                }
            }
        }
        holder.binding.root.setOnLongClickListener {
            AlertDialog.Builder(holder.itemView.context)
                .setTitle("删除消息")
                .setMessage("确定要删除这条消息吗？")
                .setPositiveButton("确定") { _, _ ->

                    mViewModel?.deleteMessage(mListData[position])
                }
                .setNegativeButton("取消", null)
                .show()
            true // 返回true表示已处理长按事件
        }

    }
}